//
//  BasicInformationController.m
//  Estate
//
//  Created by heyong on 16/6/22.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "BasicInformationController.h"
#import "DefaineCell1.h"
#import "BasicInfoHeadView.h"
#import "B_wuLiaoCell.h"
#import "UserInfoDetailTagCell.h"

@interface BasicInformationController ()
{
    FMDatabase *_db;
    DBHelper *_helper;
}

@property (strong, nonatomic)NSMutableArray *titleForSec1;
@property (strong, nonatomic)NSMutableArray *titleForSec2;
@property (strong, nonatomic)NSMutableArray *titleForSec3;
@property (strong, nonatomic)NSMutableArray *dataForSec;
@end

@implementation BasicInformationController
- (NSMutableArray *)titleForSec1{
    if(_titleForSec1==nil){
        _titleForSec1=[NSMutableArray arrayWithObjects:@"名称:",@"编号:" ,@"状态:" ,nil];
    }
    return _titleForSec1;
}

- (NSMutableArray *)titleForSec2{
    if(_titleForSec2==nil){
        _titleForSec2=[NSMutableArray arrayWithObjects:@"总监:",@"副总监:" ,@"监理员:" ,@"专业监理工程师:" ,@"监理安全工程师:" ,@"日志工程师",nil];
    }
    return _titleForSec2;
}

- (NSMutableArray *)titleForSec3{
    if(_titleForSec3==nil){
        _titleForSec3=[NSMutableArray arrayWithObjects:@"工程地点:",@"建筑规模:" ,@"施工准备期:",@"缺陷责任期:",@"施工及交工验收期:",@"合同金额:",@"投资额:",@"工程类别:",@"投资性质:",@"开工日期:",@"竣工日期:",@"项目概况",nil];
    }
    return _titleForSec3;
}

-(NSMutableArray *)dataForSec{
    if(_dataForSec==nil){
        _dataForSec=[NSMutableArray array];
    }
    return _dataForSec;
}


- (UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-104)];
//        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell1" bundle:nil] forCellReuseIdentifier:@"deCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerClass:NSClassFromString(@"UserInfoDetailTagCell") forCellReuseIdentifier:@"detail"];
    _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    _helper=[DBHelper help];
    
    [self initData];
}

#pragma mark - 初始化数据

- (void) initData{
    //查询项目表
    NSDictionary *dataDic_1= [[_helper DataBase:_db
       selectKeyTypes:@{@"PROJECT_NAME":@"text",@"PROJECT_NUMBER":@"text",@"PROJECT_STATE":@"text"}
            fromTable:PROJECT whereCondition:@{@"ID":PROID}] firstObject];
   NSString *number= dataDic_1[@"PROJECT_NUMBER"];
    NSString *state=dataDic_1[@"PROJECT_STATE"];
    
    NSArray *array_1=@[DEFISNUL(dataDic_1[@"PROJECT_NAME"]),
                       DEFISNUL(number),
                        DEFISNUL(state)];
    [self.dataForSec addObject:array_1];

    
    //查询项目人员表 SELECT USER_TYPE,USER_TYPE FROM PROJECT_USER WHERE PRO_ID='1af385c233ea45849984a085852b343b'
    //总监
    NSMutableArray *arr1=[self queryByType:@"USER_01"];
    arr1 = [arr1 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSMutableArray *arr2=[self queryByType:@"USER_02"];
    arr2 = [arr2 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSMutableArray *arr3=[self queryByType:@"USER_03"];
    arr3 = [arr3 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //专监人员
    NSMutableArray *arr7=[self queryByType:@"USER_07"];
    arr7 = [arr7 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSMutableArray *arr4=[self queryByType:@"USER_04"];
    arr4 = [arr4 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSMutableArray *arr5=[self queryByType:@"USER_05"];
    arr5 = [arr5 valueForKeyPath:@"@distinctUnionOfObjects.self"];
    NSArray *array2=@[arr1,arr2,arr3,arr7,arr4,arr5];
    
    [self.dataForSec addObject:array2];

    //查询概况表
    NSDictionary *seDic=@{@"ENGINEER_ADDRESS":@"text",
                          @"BUILDING_SCALE":@"text",
                          @"FREE_SERVICE_TIME":@"text",
                          @"GUARANTEE_TIME":@"text",
                          @"SERVICE_TIME":@"text",
                          @"CONSTRACT_AMOUNT":@"text",
                          @"INVESTMENT_AMOUNT":@"text",
                          @"ENGINEER_TYPE":@"text",
                          @"INVESTMENT_NATURE":@"text",
                          @"START_WORK_TIME":@"text",
                          @"COMPLETE_WORK_TIME":@"text",
                          @"PRO_SURVEY":@"text",
                          @"PRO_ENGINEER_DESC":@"text",
                          };
    

    //工程概览数组
    NSArray *engineerArray=[_helper DataBase:_db
                              selectKeyTypes:seDic
                                   fromTable:PRO_ENGINEER_SURVEY whereCondition:@{@"PRO_ID":PROID}];
    
    NSMutableArray *detailEngArr=[NSMutableArray array];
    
    for (NSDictionary* dataDic_3 in engineerArray) {
        //服务期添加判断
        NSString *serviceTime=@"";
        NSString *FREE_SERVICE_TIME=@"";
        NSString *GUARANTEE_TIME=@"";
        if(![dataDic_3[@"FREE_SERVICE_TIME"]isEqualToString: @""]){
            FREE_SERVICE_TIME = [dataDic_3[@"FREE_SERVICE_TIME"] substringToIndex:10];
        }
        if(![dataDic_3[@"GUARANTEE_TIME"]isEqualToString: @""]){
            GUARANTEE_TIME = [dataDic_3[@"GUARANTEE_TIME"] substringToIndex:10];
        }
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        if(![dataDic_3[@"SERVICE_TIME"]isEqualToString: @""]){
            
            NSString *time=[dataDic_3[@"SERVICE_TIME"] substringToIndex:10];
            
            NSDate *beginDate=[dateFormatter dateFromString:@"1970-01-91 00:00:00"];   //需要转化的字符串
            
            NSDate *endDate=[dateFormatter dateFromString:dataDic_3[@"SERVICE_TIME"]];
            
            BOOL is=[LSUtility date:[NSDate date] isBetweenDate:beginDate andDate:endDate];
            
            if(!is){
                serviceTime=[NSString stringWithFormat:@"%@ (已到期)",time];
            }else{
                NSInteger day =  [self getDifferenceByDate:time];
                serviceTime= [NSString stringWithFormat:@"%@(剩余%d天)",time,day];
            }
        }
//        准备期：FreeServiceTime   责任期：GuaranteeTime   验收期：ServiceTime
        NSArray *arr_3=@[DEFISNUL(dataDic_3[@"ENGINEER_ADDRESS"]),
                         DEFISNUL(dataDic_3[@"BUILDING_SCALE"]),
                         DEFISNUL(FREE_SERVICE_TIME),//2024-03-31 00:00:00
                         DEFISNUL(GUARANTEE_TIME),//2022-03-31 00:00:00
                         DEFISNUL(serviceTime),//2024-03-31 00:00:00
                         DEFISNUL(dataDic_3[@"CONSTRACT_AMOUNT"]),
                         DEFISNUL(dataDic_3[@"INVESTMENT_AMOUNT"]),
                         DEFISNUL(dataDic_3[@"ENGINEER_TYPE"]),
                         DEFISNUL(dataDic_3[@"INVESTMENT_NATURE"]),
                         DEFISNUL(dataDic_3[@"START_WORK_TIME"]),
                         DEFISNUL(dataDic_3[@"COMPLETE_WORK_TIME"]), //2022-09-07
                         DEFISNUL(dataDic_3[@"PRO_SURVEY"])];
        [detailEngArr addObject:arr_3];
    }
    
    for (NSArray *arras in detailEngArr) {
        [self.dataForSec addObject:arras];
    }
    
}
- (NSInteger)getDifferenceByDate:(NSString *)date {
    //获得当前时间
    NSDate *now = [NSDate date];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *oldDate = [dateFormatter dateFromString:date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:now  toDate:oldDate options:0];
    return [comps day];
}

//根据项目角色查询人员
- (NSMutableArray *)queryByType:(NSString *)type{
    NSString *sql=[NSString stringWithFormat:@"SELECT USER_ID FROM PROJECT_USER WHERE PRO_ID='%@' AND USER_TYPE='%@'",PROID,type];
    FMResultSet *result=[_db executeQuery:sql];
    NSMutableArray *arrName=[NSMutableArray array];
    while ([result next]) {
        NSString *userid=[result stringForColumn:@"USER_ID"];
        NSString *name=[LSUtility getuserIdByUserName:userid][@"REAL_NAME"];
        [arrName addObject:DEFISNUL(name)];
    }
    if(arrName.count<1){
        [arrName addObject:@""];
    }
    return arrName;
}


#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataForSec.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 3;
    }else if (section==1){
        return 6;
    }else{
        return 12;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(indexPath.section==0){
        NSArray *arr=self.dataForSec[indexPath.section];
        NSInteger row=indexPath.row;
        if(indexPath.row==2){
            return  [UserInfoDetailTagCell cellContentHeight:[NSString stringWithFormat:@"%@ %@",self.titleForSec1[row],[arr[row] isEqualToString:@"0"]?@"未开工":@"进行中"]];

        }else{
            return  [UserInfoDetailTagCell cellContentHeight:[NSString stringWithFormat:@"%@ %@",self.titleForSec1[row],arr[row]]];
        }
    }else if(indexPath.section==1){
        if(indexPath.row==4||indexPath.row==5){
            return 120;
        }else{
            NSArray *arr=self.dataForSec[section];
            NSArray *section2ForArr=arr[row];
            NSString *str=@"";
            for (NSString *s in section2ForArr) {
                str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",s]];
            }
            NSString *title=[NSString stringWithFormat:@"%@:%@",self.titleForSec2[row],str];
            return  [DefaineCell1 cellHeightWithObj:title];
        }
    }else{
        if(indexPath.row==11){
            return 120;
        }else
            return 44;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
    img.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    img.image=[UIImage imageNamed:@"juchishang"];
    return img;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BasicInfoHeadView *headView=[[BasicInfoHeadView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 30)];
    if(section==1){
        headView.title.text=@"人员信息";
    }else{
        headView.title.text=@"工程概况信息";
    }
    return headView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0;
    }
    return 30.;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
        
    NSArray *arr=self.dataForSec[section];
    
    if(section==0){
        
        UserInfoDetailTagCell *cell=[tableView dequeueReusableCellWithIdentifier:@"detail" forIndexPath:indexPath];
//土建(5)、路面(6)、交安(7)、交工(8)、竣工(9)
        if(row==2){
            NSString *projectState = @"";
            if([arr[row] isEqualToString:@"0"]){
                projectState = @"基础";
            }else if ([arr[row] isEqualToString:@"1"]){
                projectState = @"主体";
            }else if ([arr[row] isEqualToString:@"2"]){
                projectState = @"装修";
            }else if ([arr[row] isEqualToString:@"3"]){
                projectState = @"竣备";
            }else if ([arr[row] isEqualToString:@"4"]){
                projectState = @"已完成";
            }else if ([arr[row] isEqualToString:@"5"]){
                projectState = @"土建";
            }else if ([arr[row] isEqualToString:@"6"]){
                projectState = @"路面";
            }else if ([arr[row] isEqualToString:@"7"]){
                projectState = @"交安";
            }else if ([arr[row] isEqualToString:@"8"]){
                projectState = @"交工";
            }else if ([arr[row] isEqualToString:@"9"]){
                projectState = @"竣工";
            }
            [cell setTitleContent:[NSString stringWithFormat:@"%@ %@",self.titleForSec1[row],projectState]];
        }else{
            [cell setTitleContent:[NSString stringWithFormat:@"%@ %@",self.titleForSec1[row],arr[row]]];
        }
        
        return cell;
        
    }else if(section==1){
        
        NSArray *section2ForArr=arr[row];
        
        if(row<4){
            DefaineCell1 *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            NSString *str=@"";
            for (NSString *s in section2ForArr) {
                str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",s]];
            }
            [cell setTitle:self.titleForSec2[row] andDetail:str andLeftConstraint:5];
            
            return cell;
        }else if(row==4)
        {
            B_wuLiaoCell *textCell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            textCell.isEdit=NO;
            NSString *str=@"";
            for (NSString *s in section2ForArr) {
                str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",s]];
            }
            [textCell setTitle:self.titleForSec2[row] andPlaceHolder:@"" andTextValue:str];
            return textCell;
            
        }else
        {
            B_wuLiaoCell *textCell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            textCell.isEdit=NO;
            NSString *str=@"";
            for (NSString *s in section2ForArr) {
                str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",s]];
            }
            [textCell setTitle:self.titleForSec2[row] andPlaceHolder:@"" andTextValue:str];
            
            return textCell;
        }
        
    }else{
        if(row==11){
            B_wuLiaoCell *textCell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            textCell.isEdit=NO;
            textCell.title.text=self.titleForSec3[row];
            textCell.text.text=arr[row];
            return textCell;
        }
        
        DefaineCell1 *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
        cell.title.text = self.titleForSec3[row];
        NSString *title =arr[row];

        NSLog(@"%@",title);
        if (row == 4 && [title containsString:@"剩余"]) {
            NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc] initWithString:title];
//        attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor blackColor]}];
            [nameString addAttribute:NSForegroundColorAttributeName value:TTTheme.defaultManger.defaultColor range:NSMakeRange(11, title.length - 12)];
            cell.text.attributedText = nameString;
        }else{
            cell.text.text = title;
        }
        return cell;
      
    }
}


/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
}

@end
